//
//  Copyright © 2016年 luxiaoming. All rights reserved.
//

#import "UIButton+ImagePosition.h"

@implementation UIButton (ImagePosition)

- (void)mt_setImagePosition:(ImagePosition)postion spacing:(CGFloat)spacing {
    CGFloat imageWith = self.imageView.image.size.width;
    CGFloat imageHeight = self.imageView.image.size.height;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    CGFloat labelWidth = self.titleLabel.frame.size.width;
    CGFloat labelHeight = self.titleLabel.frame.size.height;
#pragma clang diagnostic pop
    
    CGFloat imageOffsetX = labelWidth / 2.0 ;//image中心移动的x距离
    CGFloat startY = (self.frame.size.height - imageHeight - labelHeight - spacing) / 2.0;//image中心移动的y距离
    CGFloat labelOffsetX = (imageWith + labelWidth / 2.0) - (imageWith + labelWidth) / 2.0;//label中心移动的x距离
    CGFloat endY = (self.frame.size.height + imageHeight + labelHeight + spacing) / 2.0;//label中心移动的y距离
    
    switch (postion) {
        case ImagePositionLeft:
            self.imageEdgeInsets = UIEdgeInsetsMake(0, -spacing/2.0, 0, spacing/2.0);
            self.titleEdgeInsets = UIEdgeInsetsMake(0, spacing/2.0, 0, -spacing/2.0);
            break;
            
        case ImagePositionRight:
            self.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + spacing/2, 0, -(labelWidth + spacing/2.0));
            self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageHeight + spacing/2.0), 0, imageHeight + spacing/2.0);
            break;
            
        case ImagePositionTop:
            self.titleLabel.sd_layout.centerXEqualToView(self);
            [self.titleLabel setSingleLineAutoResizeWithMaxWidth:100];
            self.imageEdgeInsets = UIEdgeInsetsMake(startY - CGRectGetMinY(self.imageView.frame), imageOffsetX, CGRectGetMinY(self.imageView.frame) - startY, -imageOffsetX);
            self.titleEdgeInsets = UIEdgeInsetsMake(endY - CGRectGetMaxY(self.titleLabel.frame), -labelOffsetX, CGRectGetMaxY(self.titleLabel.frame) - endY, labelOffsetX);
            break;
            
        case ImagePositionBottom:
            self.titleLabel.sd_layout.centerXEqualToView(self);
            [self.titleLabel setSingleLineAutoResizeWithMaxWidth:100];
            self.imageEdgeInsets = UIEdgeInsetsMake(endY - CGRectGetMaxY(self.imageView.frame), imageOffsetX, CGRectGetMaxY(self.imageView.frame) - endY, -imageOffsetX);
            self.titleEdgeInsets = UIEdgeInsetsMake(startY - CGRectGetMinY(self.titleLabel.frame), -labelOffsetX, CGRectGetMinY(self.titleLabel.frame) - startY, labelOffsetX);
            break;
            
        default:
            break;
    }
    
}

@end
